package rulerouter

import (
	"context"
	"encoding/json"
	"vpn-management-server/logger"
	"vpn-management-server/network"
	"vpn-management-server/security/code"
	"vpn-management-server/src/service/adminlogservice"
)

func RuleRouter(ctx context.Context, request *network.NetRequest, response *network.NetResponse) {
	if request.Command == "" {
		buf, _ := json.Marshal(request)
		logger.Logger.ErrorfWithIdAndConn(ctx.Value("conn_id").(string), request.GetRemote(), "Error the Request Command is Null, "+string(buf))
		response.Code = code.BAD_REQUEST
		response.ErrorMsg = "Error the Request Command is Null"
	} else {
		if f, ok := ruleRouter.HandleSet[request.Command]; !ok {
			buf, _ := json.Marshal(request)
			logger.Logger.ErrorfWithIdAndConn(ctx.Value("conn_id").(string), request.GetRemote(), "Not Supported the Request Command, "+string(buf))
			response.Code = code.BAD_REQUEST
			response.ErrorMsg = "Not Supported the Request Command"
		} else {

			isCon := true
			// 拦截请求 进行参数解析/校验/权限验证 全部通过才返回true
			if bf, ok := ruleRouter.BeforeHandleSet[request.Command]; bf != nil && ok {
				logger.Logger.Trace("start beforeHandle")
				isCon = bf(ctx, request, response)
			}

			if isCon {
				logger.Logger.Trace("start Handle")
				f(ctx, request, response)
				if response.Code == code.SUCCESS {
					if af, ok := ruleRouter.AfterHandleSet[request.Command]; af != nil && ok {
						logger.Logger.Trace("start afterHandle")
						af(ctx, request, response)
						adminlogservice.DetectLogChan()
					}
				}
			}
		}
	}
}
